package com.newcoder.community.controller;

import com.alibaba.fastjson2.JSONObject;
import com.newcoder.community.entity.Message;
import com.newcoder.community.entity.Page;
import com.newcoder.community.entity.User;
import com.newcoder.community.service.MessageService;
import com.newcoder.community.service.UserService;
import com.newcoder.community.util.CommunityConstant;
import com.newcoder.community.util.CommunityUtil;
import com.newcoder.community.util.HostHolder;
import com.sun.xml.internal.ws.api.model.MEP;
import org.springframework.aop.aspectj.annotation.MetadataAwareAspectInstanceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    //私信列表
    @RequestMapping(path = "/letter/list",method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){

        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        //查询会话列表
        List<Message> conversations = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String,Object>> conversationList = new ArrayList<>();
        if(conversations!=null){
            for(Message message:conversations){
                Map<String,Object> map = new HashMap<>();
                map.put("message",message);
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(),message.getConversationId()));
                int targetId = user.getId()==message.getFromId()?message.getToId():message.getFromId();
                map.put("target",userService.findUserById(targetId));
                conversationList.add(map);
            }
        }
        model.addAttribute("conversations",conversationList);
        //查询未读消息数目
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("unreadLetters",letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/letter";
    }
    @RequestMapping(path = "/letter/detail/{conversationId}",method = RequestMethod.GET)
    public String letterDetail(@PathVariable("conversationId") String conversationId,Model model,Page page){
           //分页信息
           page.setLimit(5);
           page.setPath("/letter/detail/"+conversationId);
           page.setRows(messageService.findLetterCount(conversationId));
           List<Message> letters = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
           User user = hostHolder.getUser();
           List<Map<String,Object>> lettersList =  new ArrayList<>();
           if(letters!=null){
               for(Message message:letters){
                   Map<String,Object> map = new HashMap<>();
                   map.put("letter",message);
                   map.put("fromUser",userService.findUserById(message.getFromId()));
                   lettersList.add(map);
               }
           }
           model.addAttribute("letters",lettersList);
           model.addAttribute("user",user);
           User letterTarget = getLetterTarget(conversationId);
           model.addAttribute("target",letterTarget);
           //设置已读
        List<Integer> letterIds = getLetterIds(letters);
        if(!letterIds.isEmpty()){
            messageService.readMessage(letterIds);
        }
        return "/site/letter-detail";

    }
    private List<Integer> getLetterIds(List<Message> messages){
        List<Integer> letterIds  = new ArrayList<>();
        if(messages!=null){
            for(Message message:messages){
                if(hostHolder.getUser().getId()==message.getToId()&&message.getStatus()==0){
                    letterIds.add(message.getId());
                }
            }
        }
        return letterIds;
    }
    private  User getLetterTarget(String conversationId){
         String[] ids = conversationId.split("_");
         int id0 = Integer.parseInt(ids[0]);
         int id1 = Integer.parseInt(ids[1]);
         if(hostHolder.getUser().getId()==id0){
             return userService.findUserById(id1);
         }else {
             return userService.findUserById(id0);
         }
    }
    @RequestMapping(path = "/letter/send",method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName,String content){
         User userByUsername = userService.findUserByUsername(toName);
         if(userByUsername==null){
             return CommunityUtil.getJsonString(1,"目标用户不存在");
         }
         Message message = new Message();
         message.setToId(userByUsername.getId());
         message.setFromId(hostHolder.getUser().getId());
         if(message.getFromId()<message.getToId()){
             message.setConversationId(message.getFromId()+"_"+message.getToId());
         }else{
             message.setConversationId(message.getToId()+"_"+message.getFromId());
         }
         message.setCreateTime(new Date());
         message.setContent(content);
         messageService.addMessage(message);
         return CommunityUtil.getJsonString(0);
    }
    @RequestMapping(path ="/notice/list",method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();
        //查询评论类的通知
        Message message = messageService.findLatestNotice(user.getId(),TOPIC_COMMENT);
        Map<String,Object> messageVO = new HashMap<>();
        if(message!=null){
            messageVO.put("message",message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(),TOPIC_COMMENT);
            messageVO.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unread",unread);
            model.addAttribute("commentNotice",messageVO);
        }

        //查询点赞类的通知
        message = messageService.findLatestNotice(user.getId(),TOPIC_LIKE);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message",message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(),TOPIC_LIKE);
            messageVO.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread",unread);
            model.addAttribute("likeNotice",messageVO);
        }

        //查询关注类的通知
        message = messageService.findLatestNotice(user.getId(),TOPIC_FOLLOW);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message",message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
//            messageVO.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(),TOPIC_FOLLOW);
            messageVO.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread",unread);
            model.addAttribute("followNotice",messageVO);
        }

        //查询未读消息总数
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/notice";
    }
    @RequestMapping(path = "/notice/detail/{topic}",method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic,Model model,Page page){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/notice/detail/"+topic);
        page.setRows(messageService.findNoticeCount(user.getId(),topic));
        List<Message> notices = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String,Object>> noticeVO = new ArrayList<>();
        if(notices!=null){
            for(Message message:notices){
                Map<String,Object> map = new HashMap<>();
                map.put("message",message);
                String content = HtmlUtils.htmlUnescape(message.getContent());
                Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
                map.put("user",userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("postId",data.get("postId"));
                //通知作者
                map.put("fromUser",userService.findUserById(message.getFromId()));
                noticeVO.add(map);
            }
        }
        model.addAttribute("notices",noticeVO);
        //设置已读
        List<Integer> letterIds = getLetterIds(notices);
        if(!letterIds.isEmpty()){
            messageService.readMessage(letterIds);
        }
        return "/site/notice-detail";
    }
}

